package com.easy.carpanel.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.weather.LocalDayWeatherForecast;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.easy.carpanel.R;
import com.easy.carpanel.uart.uartJni;
import com.easy.carpanel.until.CarUtil;
import com.easy.carpanel.util.HttpHelper;
import com.easy.carpanel.util.UIHelper;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import org.apache.http.Header;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class CarActivity extends AppCompatActivity implements WeatherSearch.OnWeatherSearchListener{
    int bpvalue = 79;  //bp值
    int hrvalue = 65;// hr值
    int tvalue= 36; //t值
    int pressurevalue = 980; //压强参数

    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.tv2)
    TextView tv2;

    @BindView(R.id.bptextview)
    TextView bptextview;     //bp 参数
    @BindView(R.id.hrtextview)
    TextView hrtextview;      //hr 参数
    @BindView(R.id.ttextview)
    TextView ttextview;       //t 参数
    @BindView(R.id.temperaturetextview)
    TextView temperaturetextview;  //温度
    @BindView(R.id.pressuretextview)
    TextView pressuretextview;    //压强
    @BindView(R.id.healthImageView)
    GifImageView healthImageView;      //hr 参数

    GifDrawable gifDrawable;


    @BindView(R.id.img_weather)
    ImageView imgWeather;      //天气图片
    private boolean isFristWeather = true;
    private String addresscode;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    private Runnable readerRunnable;
    private Runnable weatherRunnable;
    byte[] read_buf = new byte[1024];
    Handler handler = new Handler();
    int fd;


    private WeatherSearchQuery mquery;
    private WeatherSearch mweathersearch;
    private LocalWeatherLive weatherlive;

    private static final int CODE = 1000;

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car);

        context = this;

        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        bptextview.setText(bpvalue + "");
        hrtextview.setText(hrvalue + "");
        ttextview.setText(tvalue + "");
        pressuretextview.setText(pressurevalue + "hpa");


        gifDrawable = (GifDrawable) healthImageView.getDrawable();
        gifDrawable.start();

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.setLocationOption(mLocationOption);
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //申请的权限全部允许
                    //给定位客户端对象设置定位参数
                    mLocationClient.setLocationOption(mLocationOption);
                    //启动定位
                    mLocationClient.startLocation();

                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(CarActivity.this, "GPS定位权限没有打开，请打开！", Toast.LENGTH_SHORT).show();
                }
            }
        });



        Login("", "");
    }


//    @OnClick(R.id.hrtextview)
//    public void onViewClicked() {
//        Intent intent = new Intent(CarActivity.this, BmpActivity.class);
//        startActivity(intent);
//    }


    @Override
    protected void onResume() {
        String device = "/dev/ttyS3";
        fd = uartJni.open(device, 115200);
        Log.e("jiangyunwei", "open the device of " + device + ", fd is: " + fd);

        readerRunnable = new Runnable() {
            @Override
            public void run() {
                int read_count = uartJni.read(fd, read_buf, read_buf.length);

                Log.e("read===","==="+read_count);

                if (read_count < 0) {
                    read_count = 0;
                }
                String  value =  CarUtil.toHex(read_buf, read_count);
                Log.e("read===1","==="+value);
//                System.out.println(value);
                List<String> list = CarUtil.getStrList(value,2);

                if(list.size()>0){
                    Log.e("read===2",list.size()+"==="+list.get(0)+"==="+Long.parseLong(list.get(23),  16)+"==="+Long.parseLong(list.get(25),  16)+"==="+list);
                }


                if(list==null || list.size()<=8){
                    handler.postDelayed(this, 500);
                    return;
                }
                if(list.size()>=28){
                    int  tag = (int) Long.parseLong(list.get(27),16);
                    if(tag == 0){
                        CarActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                Intent    intent  =  new Intent(CarActivity.this,BmpActivity.class);
//                                CarActivity.this.startActivity(intent);
                            }
                        });
                    }
                }

                int tvalue1 =  (int) Long.parseLong(list.get(22),  16);
                int tvalue2 =  (int) Long.parseLong(list.get(23),  16);
                hrvalue  = tvalue1+ tvalue2*10/256 ;

                tvalue1 =  (int) Long.parseLong(list.get(24),  16);
                tvalue2 =  (int) Long.parseLong(list.get(25),  16);
                bpvalue  = tvalue1+ tvalue2*10/256 ;

                tvalue1 =  (int) Long.parseLong(list.get(24),  16);
                tvalue2 =  (int) Long.parseLong(list.get(25),  16);
                tvalue  = tvalue1+ tvalue2*10/256 ;

                tvalue1 =  (int) Long.parseLong(list.get(18),  16);
                tvalue2 =  (int) Long.parseLong(list.get(19),  16);
                pressurevalue  = tvalue1+ tvalue2*10/256 ;


                if (!(hrvalue + "").equals(hrtextview.getText())) {
//                    healthImageView.setImageResource(R.drawable.heath_animation);
//                    AnimationDrawable animationDrawable = (AnimationDrawable) healthImageView.getDrawable();
//                    animationDrawable.start();

//                    healthImageView.setImageResource(R.mipmap.healthgif);
                    gifDrawable.start();

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            CarActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    gifDrawable.stop();
//                                    healthImageView.setImageResource(R.mipmap.healthbd);
                                }
                            });
                        }
                    }, 5000);
                }

                bptextview.setText(bpvalue+"");
                hrtextview.setText(hrvalue+"");
                ttextview.setText(tvalue+"");
                pressuretextview.setText(pressurevalue+"hpa");

                handler.postDelayed(this, 500);
                //相当于定时器，每隔1s执行一次该线程
            }
        };
        handler.post(readerRunnable);

        super.onResume();
    }

    @Override
    protected void onPause() {
        uartJni.close(fd);
        handler.removeCallbacks(readerRunnable);
        handler.removeCallbacks(weatherRunnable);
        super.onPause();
    }


    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

            if (isFristWeather) {
                isFristWeather = false;

                Log.e("mLocationListener===", aMapLocation.getCityCode()+"==="+aMapLocation.getCity());

                addresscode = aMapLocation.getAdCode();
                initweather(addresscode, aMapLocation.getCity());



            }


        }
    };


    private void initweather(String addresscode, String city) {

        //实时
        mquery = new WeatherSearchQuery(addresscode, WeatherSearchQuery.WEATHER_TYPE_LIVE);
        mweathersearch = new WeatherSearch(this);
        mweathersearch.setOnWeatherSearchListener(this);
        mweathersearch.setQuery(mquery);
        //异步搜索
        mweathersearch.searchWeatherAsyn();

        //预报未来几天
        mquery = new WeatherSearchQuery(addresscode, WeatherSearchQuery.WEATHER_TYPE_FORECAST);
        mweathersearch = new WeatherSearch(this);
        mweathersearch.setOnWeatherSearchListener(this);
        mweathersearch.setQuery(mquery);
        //异步搜索
        mweathersearch.searchWeatherAsyn();

//        Login(addresscode, city);

//        pm();




//        Log.e("addresscode===", "==="+addresscode);
//
////        url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=f0f577c0b97d416f142fed74e8bbd3d7&ids=70037&_=1554559702415"
////        header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0"}
//
//        OkHttpClient client = new OkHttpClient();
//        //110000 150200
//        String url = "https://restapi.amap.com/v3/weather/weatherInfo?" + "key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + addresscode;
////        String url = "https://qsued-teams.github.io/location-weather-airQuality/dist/index.html#/index";
////        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + addresscode;
////        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&ids=70037";
////        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&citycode=" + addresscode;
////        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=f0f577c0b97d416f142fed74e8bbd3d7&zoom=11&bounds=114.081939%2C30.640691%3B114.619326%2C30.487053&citycode=420100";
////        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=0ccb4f953a8b57bab10919ec97c18b2a";
////        String url = "http://php.weather.sina.com.cn/xml.php?city=武汉&password=DJOYnieT8234jlsK&day=0";
////        String url = "http://xoap.weather.com/weather/local/CHXX0138?cc=*&unit=m&dayf=2&link=xoap&prod=xoap&par=1220552427&key=c168fcf83120f8ed";
////        String url = "http://www.google.com/ig/api?weather=Beijing";
////        String url = "https://www.tianqiapi.com/api?version=v10&appid=79947512&appsecret=bj3ngfAn";
////        String url = "https://www.tianqiapi.com/api?version=v61&appid=79947512&appsecret=bj3ngfAn";
//
//        Request request = new Request.Builder().get().url(url).build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                Log.e("weather===", "==="+response);
//
//                //一般会得到Json数据，这时候就要用Json解析的一系列方法处理了，网上都可查这里不多讲
//                String jsonString = response.body().string();
//                //把访问url得到的数据打印出来
//                JSONObject json = JSONObject.parseObject(jsonString);
//                JSONArray livejson = json.getJSONArray("lives");
//                if (livejson == null) {
//                    return;
//                }
//                String weather = livejson.getJSONObject(0).getString("weather");
//                String temperature = livejson.getJSONObject(0).getString("temperature");
//
//                Log.e("weather===1", livejson+"==="+temperature+"==="+weather);
//
//                CarActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        temperaturetextview.setText(temperature + "℃");
//                    }
//                });
//                if (weather.contains("晴")) {
//                    CarActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            imgWeather.setImageResource(R.mipmap.qing);
//                        }
//                    });
//                }
//                if (weather.contains("多云")) {
//                    CarActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            imgWeather.setImageResource(R.mipmap.duoyun);
//                        }
//                    });
//
//                }
//                if (weather.contains("阴")) {
//                    CarActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            imgWeather.setImageResource(R.mipmap.yin);
//                        }
//                    });
//
//                }
//                if (weather.equals("雨夹雪")) {
//                    CarActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            imgWeather.setImageResource(R.mipmap.yujiaxue);
//                        }
//                    });
//                } else if (weather.contains("雷")) {
//                    CarActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            imgWeather.setImageResource(R.mipmap.leiyu);
//                        }
//                    });
//                } else if (weather.contains("雪")) {
//                    CarActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            imgWeather.setImageResource(R.mipmap.daxue);
//                        }
//                    });
//                }
//            }
//        });

    }

    void pm(){
        String url = "https://api.apishop.net/common/postcode/getPostCodeByAddr";
        String requestMethod = "GET";
        Map<String, String> params = new HashMap<String, String>();
        params.put("city", "常州市"); //城市，如“广州市”
        String result = "";
        try
        {
            Log.e("result===", "==="+result);

            InputStream is = httpRequestToStream(url, requestMethod, params);
            byte[] b = new byte[is.available()];
            is.read(b);
            result = new String(b);

            Log.e("result===1", "==="+result);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        if (result != null)
        {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String status_code = jsonObject.getString("statusCode");
            if (status_code == "000000")
            {
                // 状态码为000000, 说明请求成功
                System.out.println("请求成功：" + jsonObject.getString("result"));
            }
            else
            {
                // 状态码非000000, 说明请求失败
                System.out.println("请求失败：" + jsonObject.getString("desc"));
            }
        }
        else
        {
            // 返回内容异常，发送请求失败，以下可根据业务逻辑自行修改
            System.out.println("发送请求失败");
        }
    }

    private void Login(String addresscode, String city) {

        Log.e("Login===", addresscode+"==="+city);

        RequestParams params = new RequestParams();
        params.add("version", "v61");
        params.add("appid", "79947512");
        params.add("appsecret", "bj3ngfAn");
//        try {
//            params.add("city", URLEncoder.encode("常州市", "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        params.add("telpass", telpassEdit.getText().toString());

//        String url = "https://restapi.amap.com/v3/weather/weatherInfo?" + "key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + addresscode;
//        String url = "https://qsued-teams.github.io/location-weather-airQuality/dist/index.html#/index";
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?key=0ccb4f953a8b57bab10919ec97c18b2a&ids=" + addresscode;
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + addresscode;
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&ids=70037";
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&citycode=" + addresscode;
//        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=f0f577c0b97d416f142fed74e8bbd3d7&zoom=11&bounds=114.081939%2C30.640691%3B114.619326%2C30.487053&citycode=" + addresscode;    //420100
//        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=f0f577c0b97d416f142fed74e8bbd3d7&zoom=11&citycode=420100";
//        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=0ccb4f953a8b57bab10919ec97c18b2a";
//        String url = "http://php.weather.sina.com.cn/xml.php?city=武汉&password=DJOYnieT8234jlsK&day=0";
//        String url = "http://xoap.weather.com/weather/local/CHXX0138?cc=*&unit=m&dayf=2&link=xoap&prod=xoap&par=1220552427&key=c168fcf83120f8ed";
//        String url = "http://www.google.com/ig/api?weather=Beijing";
//        String url = "https://www.tianqiapi.com/api?version=v10&appid=79947512&appsecret=bj3ngfAn";
//        String url = "https://www.tianqiapi.com/api?version=v61&appid=79947512&appsecret=bj3ngfAn&city="+city.substring(0, city.length()-1);
//        String url = "https://www.tianqiapi.com/api?version=v61&appid=79947512&appsecret=bj3ngfAn&cityEn=changzhou";
//        String url = "https://www.tianqiapi.com/api";
//        String url = "http://api.lib360.net/open/pm2.5.json?city=苏州";
//        String url = "https://api.apishop.net/common/postcode/getPostCodeByAddr";
        String url = "https://www.tianqiapi.com/ip";

        HttpHelper.post(context, url,  params, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                m_myHandler.post(new Runnable() {
                    @Override
                    public void run() {
//                        if (loadingDialog != null && !loadingDialog.isShowing()) {
//                            loadingDialog.setTitle("请稍等");
//                            loadingDialog.show();
//                        }
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                m_myHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("Login===f", throwable.toString()+"==="+responseString);

//                        if (loadingDialog != null && loadingDialog.isShowing()){
//                            loadingDialog.dismiss();
//                        }
                        UIHelper.ToastError(context, throwable.toString());

//                        finish();
                    }
                });
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, final String responseString) {
                m_myHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {

//                                ResultConsel result = JSON.parseObject(responseString, ResultConsel.class);

                            Log.e("Login===1", "".equals(responseString)+"==="+responseString);

                            JSONObject json = JSON.parseObject(responseString, JSONObject.class);

                            Log.e("Login===2", "==="+json.getString("ip"));

//                            tv.setText(""+responseString);

                            air(json.getString("ip"));

//                            UserBean bean = JSON.parseObject(responseString, UserBean.class);
//
//                            Log.e("conectDevice===2", bean.getId()+"===");

//                            if("".equals(responseString)){
//                                ToastUtil.showMessageApp(context, "账号或密码不正确");
//                            }else{
//                                ToastUtil.showMessageApp(context, "登录成功");
//
////                                initData();
//
//                                SharedPreferencesUrls.getInstance().putString("telephone", telephoneEdit.getText().toString());
//
//                                Intent intent = new Intent();
//                                intent.setClass(context, DeviceLoginActivity.class);
//                                intent.putExtra("telephone", telephoneEdit.getText().toString());
//                                startActivity(intent);
//
////                                IntentUtils.startActivity(activity, DeviceLoginActivity.class);
//                                finishMine();
//                            }


                        } catch (Exception e) {
                            Log.e("conectDevice===e", "==="+e);
                            e.printStackTrace();
                        }

//                        if (loadingDialog != null && loadingDialog.isShowing()) {
//                            loadingDialog.dismiss();
//                        }
                    }
                });

            }


        });

    }

    private void air(String ip) {

        Log.e("air===", "==="+ip);

        RequestParams params = new RequestParams();
        params.add("version", "v61");
        params.add("appid", "79947512");
        params.add("appsecret", "bj3ngfAn");
        params.add("ip", ip);
//        try {
//            params.add("city", URLEncoder.encode("常州市", "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        params.add("telpass", telpassEdit.getText().toString());

//        String url = "https://restapi.amap.com/v3/weather/weatherInfo?" + "key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + addresscode;
//        String url = "https://qsued-teams.github.io/location-weather-airQuality/dist/index.html#/index";
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?key=0ccb4f953a8b57bab10919ec97c18b2a&ids=" + addresscode;
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + addresscode;
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&ids=70037";
//        String url = "https://restapi.amap.com/v3/airquality/aqidetail?callback=jQuery214041126974549961415_1554559702413&key=0ccb4f953a8b57bab10919ec97c18b2a&citycode=" + addresscode;
//        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=f0f577c0b97d416f142fed74e8bbd3d7&zoom=11&bounds=114.081939%2C30.640691%3B114.619326%2C30.487053&citycode=" + addresscode;    //420100
//        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=f0f577c0b97d416f142fed74e8bbd3d7&zoom=11&citycode=420100";
//        String url = "https://restapi.amap.com/v3/airquality/aqilist?key=0ccb4f953a8b57bab10919ec97c18b2a";
//        String url = "http://php.weather.sina.com.cn/xml.php?city=武汉&password=DJOYnieT8234jlsK&day=0";
//        String url = "http://xoap.weather.com/weather/local/CHXX0138?cc=*&unit=m&dayf=2&link=xoap&prod=xoap&par=1220552427&key=c168fcf83120f8ed";
//        String url = "http://www.google.com/ig/api?weather=Beijing";
//        String url = "https://www.tianqiapi.com/api?version=v10&appid=79947512&appsecret=bj3ngfAn";
//        String url = "https://www.tianqiapi.com/api?version=v61&appid=79947512&appsecret=bj3ngfAn&city="+city.substring(0, city.length()-1);
//        String url = "https://www.tianqiapi.com/api?version=v61&appid=79947512&appsecret=bj3ngfAn&cityEn=changzhou";
//        String url = "https://www.tianqiapi.com/api";
//        String url = "http://api.lib360.net/open/pm2.5.json?city=苏州";
//        String url = "https://api.apishop.net/common/postcode/getPostCodeByAddr";
//        String url = "https://www.tianqiapi.com/ip";
//        String url = "https://www.tianqiapi.com/api?version=v61&appid=79947512&appsecret=bj3ngfAn&ip="+ip;
        String url = "https://www.tianqiapi.com/api?version=v9&appid=79947512&appsecret=bj3ngfAn";

        HttpHelper.get(context, url,  params, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                m_myHandler.post(new Runnable() {
                    @Override
                    public void run() {
//                        if (loadingDialog != null && !loadingDialog.isShowing()) {
//                            loadingDialog.setTitle("请稍等");
//                            loadingDialog.show();
//                        }
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                m_myHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("air===f", throwable.toString()+"==="+responseString);

//                        if (loadingDialog != null && loadingDialog.isShowing()){
//                            loadingDialog.dismiss();
//                        }
                        UIHelper.ToastError(context, throwable.toString());

//                        finish();
                    }
                });
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, final String responseString) {
                m_myHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {

//                                ResultConsel result = JSON.parseObject(responseString, ResultConsel.class);

                            Log.e("air===1", "".equals(responseString)+"==="+responseString);

                            tv.setText(""+responseString);

//                            UserBean bean = JSON.parseObject(responseString, UserBean.class);
//
//                            Log.e("conectDevice===2", bean.getId()+"===");

//                            if("".equals(responseString)){
//                                ToastUtil.showMessageApp(context, "账号或密码不正确");
//                            }else{
//                                ToastUtil.showMessageApp(context, "登录成功");
//
////                                initData();
//
//                                SharedPreferencesUrls.getInstance().putString("telephone", telephoneEdit.getText().toString());
//
//                                Intent intent = new Intent();
//                                intent.setClass(context, DeviceLoginActivity.class);
//                                intent.putExtra("telephone", telephoneEdit.getText().toString());
//                                startActivity(intent);
//
////                                IntentUtils.startActivity(activity, DeviceLoginActivity.class);
//                                finishMine();
//                            }


                        } catch (Exception e) {
                            Log.e("conectDevice===e", "==="+e);
                            e.printStackTrace();
                        }

//                        if (loadingDialog != null && loadingDialog.isShowing()) {
//                            loadingDialog.dismiss();
//                        }
                    }
                });

            }


        });

    }


    /**
     * 方法体说明：向远程接口发起请求，返回字节流类型结果
     * param url 接口地址
     * param requestMethod 请求方式
     * param params 传递参数     重点：参数值需要用Base64进行转码
     * return InputStream 返回结果
     */
    public static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params)
    {
        InputStream is = null;
        try
        {
            String parameters = "";
            boolean hasParams = false;
            // 将参数集合拼接成特定格式，如name=zhangsan&age=24
            for (String key : params.keySet())
            {
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key + "=" + value + "&";
                hasParams = true;
            }
            if (hasParams)
            {
                parameters = parameters.substring(0, parameters.length() - 1);
            }

            // 请求方式是否为get
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            // 请求方式是否为post
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            if (isGet)
            {
                url += "?" + parameters;
            }

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();

            // 请求的参数类型(使用restlet框架时，为了兼容框架，必须设置Content-Type为“”空)
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置连接超时时间
            conn.setConnectTimeout(50000);
            // 设置读取返回内容超时时间
            conn.setReadTimeout(50000);
            // 设置向HttpURLConnection对象中输出，因为post方式将请求参数放在http正文内，因此需要设置为ture，默认false
            if (isPost)
            {
                conn.setDoOutput(true);
            }
            // 设置从HttpURLConnection对象读入，默认为true
            conn.setDoInput(true);
            // 设置是否使用缓存，post方式不能使用缓存
            if (isPost)
            {
                conn.setUseCaches(false);
            }
            // 设置请求方式，默认为GET
            conn.setRequestMethod(requestMethod);

            // post方式需要将传递的参数输出到conn对象中
            if (isPost)
            {
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(parameters);
                dos.flush();
                dos.close();
            }

            // 从HttpURLConnection对象中读取响应的消息
            // 执行该语句时才正式发起请求
            is = conn.getInputStream();
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch(MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return is;
    }



    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {


                default:
                    break;
            }
            return false;
        }
    });


    @Override
    public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) {
        if (rCode == CODE) {
            if (weatherLiveResult != null && weatherLiveResult.getLiveResult() != null) {
                weatherlive = weatherLiveResult.getLiveResult();

                Log.e("liveSearched===", weatherlive.getProvince()+"===" + weatherlive.getCity()+"===" + weatherlive.getWeather()+"===" +weatherlive.getTemperature() +"===" + weatherlive.getWindDirection() +"===" + weatherlive.getHumidity());

                tv.setText(weatherlive.getReportTime()+"===" + weatherlive.getProvince()+"===" + weatherlive.getCity()+"===" + weatherlive.getWeather()+"===" +weatherlive.getTemperature() +"===" + weatherlive.getWindDirection() +"===" + weatherlive.getHumidity());

//                tvCity.setText(weatherlive.getCity());
//                tvWeatherCondition.setText(weatherlive.getWeather());
//                //气温
//                tvMinimumDegrees.setText(weatherlive.getTemperature() + "°");
//                tvWind.setText(weatherlive.getWindDirection() + "风" + weatherlive.getWindPower() + "级");
//                tvHumidity.setText("湿度     " + weatherlive.getHumidity() + "%");
//                tvUpdate.setText("更新于:" + weatherlive.getReportTime());
            } else {
                Log.e("实时天气", "onWeatherLiveSearched: ------------------实时天气------------------" + weatherLiveResult);
            }
        }
    }

    @Override
    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int index) {
        //这个地方需要注意下 是取的getWeatherForecast()
        List<LocalDayWeatherForecast> local = localWeatherForecastResult.getForecastResult().getWeatherForecast();

        for(int i=0; i<local.size(); i++){
            Log.e("forecast===", i +"==="+ local.get(i).getWeek() +"==="+ local.get(i).getDayTemp() +"==="+ local.get(i).getNightTemp() +"==="+ local.get(i).getDayWeather() +"==="+ local.get(i).getDate());

            if(i==0){
                tv2.setText(local.get(i).getWeek() +"==="+ local.get(i).getDayTemp() +"==="+ local.get(i).getNightTemp() +"==="+ local.get(i).getDayWeather() +"==="+ local.get(i).getDate());
            }

        }



//        this.data=local;
//        homeWeatherAdapter.update(data);
    }
}
